<?php

//Mail is unique
require 'mail/enviar.php';

//sendMail(1);
function sendMail($accountNumber) {
    $headers = 'From: webmaster@sexample.com' . "\r\n" .
            'Reply-To: webmaster@example.com' . "\r\n" .
            'X-Mailer: PHP/' . phpversion();
    $username = getUserName(getAccntId($accountNumber));
    $msg = "Hola, estos son los codigos de seguridad que puede usar para sus transacciones: \n\n";



    $mail = getMail($username);
    $ids = array();
    for ($i = 0; $i < 100; $i++) {
        $nid = getNextId($i, $mail) . "";
        // $//msg.=$nid;
        $sub = "Códigos de Transacción - Internet Banking System";
        $ids[$i] = $nid;
    }

    $origen = "c:/temp/" . md5($ids[1]);
    $destino = "c:/temp/" . md5($ids[2]);


  

    $rest = substr(md5($ids[1] . "" . $ids[3]), 7);
    $msg.="Su password aleatoria es: ".$rest;



    getEncodedPdf($origen . ".pdf", $destino . "sec.pdf",$rest, $ids);
    //If you want, u can compare it wiidcuenth the db, but mostly each one is unique
    mandarMail($mail, $sub, $msg, $destino . "sec.pdf");
    //Just to guarantee atomicity
    foreach ($ids as $item) {
        addToDB($item, $accountNumber);
    }
}

//This should be always unique, there's only one mail, one unique number per code, and i've added 2 rands
//plus, this is MD5 that sould make a unique hash (i know its already broken but...)      
function getNextId($i, $mail) {
    initRand();
    $hash = hash('MD5', rand(0, getrandmax()) . $i . $mail . rand(0, getrandmax()));
    //EMPANADAAA
    $hash = substr($hash, 0, 15);
    return $hash;
}

function initRand() {
    static $randCalled = FALSE;
    if (!$randCalled) {
        srand((double) microtime() * 1000000);
        $randCalled = TRUE;
    }
}

//Empanada!!! dafuq con conectarse kda vez?!
function getMail($username) {
    $url = "localhost";
    $user = "root";
    $pass = "";
    $db = "banco";
    $mysqli = new mysqli($url, $user, $pass, $db);
    if ($mysqli->connect_errno) {
        echo "Failed to connect to MySQL: ";
    }
    /* Prepared statement, stage 1: prepare */
    if (!($stmt = $mysqli->prepare("SELECT email FROM usuario WHERE username = ?"))) {
        echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
    }
    $stmt->bind_param("s", $username);
    /* execute query */
    $stmt->execute();
    /* bind result variables */
    $stmt->bind_result($mail);
    /* fetch value */
    $stmt->fetch();
    try {
        $stmt->close();
        $mysqli->close();
    } catch (Exception $e) {
        
    }
    return $mail;
}

function getUserName($id) {
    $url = "localhost";
    $user = "root";
    $pass = "";
    $db = "banco";

    $mysqli = new mysqli($url, $user, $pass, $db);
    if ($mysqli->connect_errno) {
        echo "Failed to connect to MySQL: ";
    }
    /* Prepared statement, stage 1: prepare */
    if (!($stmt = $mysqli->prepare("SELECT username FROM usuario u WHERE u.id = (SELECT idpropietario FROM cuenta c WHERE c.id = ?)"))) {
        echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
        return -1;
    }
    $stmt->bind_param("i", $id);
    /* execute query */
    $stmt->execute();
    /* bind result variables */
    $stmt->bind_result($id2);
    /* fetch value */
    $stmt->fetch();
    try {
        $stmt->close();
        $mysqli->close();
    } catch (Exception $e) {
        
    }
    return $id2;
}

function getAccntId($accnt) {
    $url = "localhost";
    $user = "root";
    $pass = "";
    $db = "banco";
    $mysqli = new mysqli($url, $user, $pass, $db);
    if ($mysqli->connect_errno) {
        echo "Failed to connect to MySQL: ";
    }
    /* Prepared statement, stage 1: prepare */
    if (!($stmt = $mysqli->prepare("SELECT id FROM cuenta WHERE numero = ?"))) {
        echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
        return -1;
    }
    $stmt->bind_param("s", $accnt);
    /* execute query */
    $stmt->execute();
    /* bind result variables */
    $stmt->bind_result($id);
    /* fetch value */
    $stmt->fetch();
    try {
        $stmt->close();
        $mysqli->close();
    } catch (Exception $e) {
        return -1;
    }
    return $id;
}

function addToDB($tok, $accnt) {
    $url = "localhost";
    $user = "root";
    $pass = "";
    $db = "banco";
    $mysqli = new mysqli($url, $user, $pass, $db);
    if ($mysqli->connect_errno) {
        echo "Failed to connect to MySQL: ";
        return;
    }
    /* Prepared statement, stage 1: prepare */
    if (!($stmt = $mysqli->prepare("INSERT INTO tokens VALUES (NULL,?,?,false,NULL)"))) {
        echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
        return;
    }
    /* Prepared statement, stage 2: bind and execute */
    if (!$stmt->bind_param("is", getAccntId($accnt), $tok)) {
        echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
        return;
    }
    if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error . " " . $tok . " " . getAccntId($accnt);
        return;
    }
    try {
        $stmt->close();
        $mysqli->close();
    } catch (Exception $e) {
        
    }
}

?>
